package com.ldk.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alipay.util.AlipayCore;
import com.alipay.util.AlipayNotify;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.framework.entity.Alipay;
import com.ldk.framework.entity.Tenpay;
import com.ldk.framework.service.IAlipayService;
import com.ldk.framework.service.IRechargeOrderService;
import com.ldk.framework.service.IServiceTripService;
import com.ldk.framework.service.ITenpayService;
import com.thoughtworks.xstream.XStream;
import com.weixin.api.WxMpInMemoryConfigStorage;
import com.weixin.api.WxMpService;
import com.weixin.api.WxMpServiceImpl;
import com.weixin.bean.result.NotifyMpPayResult;
import com.weixin.common.util.xml.XStreamInitializer;
import com.weixin.util.WxConfig;

/**
 * 行程定金支付通知控制器
 * @author xiangwl
 *
 */
@Controller
@RequestMapping("/deposit/paynotify")
public class DepositPayNotifyController extends BaseController {
	
	@Autowired
	private ITenpayService tenpayService;
	@Autowired
	private IAlipayService alipayService;
	@Autowired
	private IRechargeOrderService rechargeOrderService;
	@Autowired
	private IServiceTripService serviceTripService;
	

	/**
	 * 支付宝支付通知回调接口
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/alipay",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
	public void alipay(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		//获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter
				.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		//logger.error("paynotify:deposit:alipay:params="+params.toString());
		
		boolean flag = false;
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号 String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

		// 支付宝交易号 String trade_no = new
		// String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		logger.error("paynotify:deposit:alipay:verify:start");
		if (AlipayNotify.verify(params)) {// 验证成功
			// ////////////////////////////////////////////////////////////////////////////////////////
			logger.error("paynotify:deposit:alipay:verify:success");
			// 请在这里加上商户的业务逻辑程序代码
			// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//解析参数
			String notifyId = getMapValue(params, "notify_id");
//			String appId = getMapValue(params, "app_id");
			String buyerId = getMapValue(params, "buyer_id");
			String body = getMapValue(params, "body");
			String tradeNo = getMapValue(params, "trade_no");
			String useCoupon = getMapValue(params, "use_coupon");
			String notifyTime = getMapValue(params, "notify_time");
			String subject = getMapValue(params, "subject");
			String signType = getMapValue(params, "sign_type");
			String s_total_fee_adjust = getMapValue(params, "s_total_fee_adjust");
			String notifyType = getMapValue(params, "notify_type");
			String outTradeNo = getMapValue(params, "out_trade_no");
			String tradeStatus = getMapValue(params, "trade_status");
			String sign = getMapValue(params, "sign");
			String gmtCreate = getMapValue(params, "gmt_create");//交易创建时间
			String sellerId = getMapValue(params, "seller_id");
			String buyerEmail = getMapValue(params, "buyer_email");
			String discount = getMapValue(params, "discount");
			String sellerEmail = getMapValue(params, "seller_email");
			double price = ConvertUtil.parseDouble(params.get("receipt_amount"));//新版实收价格回调参数已变// ConvertUtil.parseDouble(params.get("price"));
			double totalFee = ConvertUtil.parseDouble(params.get("total_amount"));//新版订单金额回调参数已变// ConvertUtil.parseDouble(params.get("total_fee"));
			long paymentType = ConvertUtil.parseLong(params.get("payment_type"));//此参数在新版中取消
			
			//支付宝记录实体
			Alipay alipay = new Alipay();
			alipay.setNotifyId(notifyId);
			alipay.setOutTradeNo(outTradeNo);
			alipay.setBuyerId(buyerId);
			alipay.setBody(body);
			alipay.setTradeNo(tradeNo);
			alipay.setUseCoupon(useCoupon);
			alipay.setNotifyTime(notifyTime);
			alipay.setSubject(subject);
			alipay.setSignType(signType);
			alipay.setSTotalFeeAdjust(s_total_fee_adjust);
			alipay.setNotifyType(notifyType);
			alipay.setTradeStatus(tradeStatus);
			alipay.setSign(sign);
			alipay.setGmtCreate(gmtCreate);
			alipay.setSellerId(sellerId);
			alipay.setBuyerEmail(buyerEmail);
			alipay.setDiscount(discount);
			alipay.setPrice(price);
			alipay.setTotalFee(totalFee);
			alipay.setPaymentType(paymentType);
			alipay.setSellerEmail(sellerEmail);
			logger.error("paynotify:deposit:alipay:verify:trade_status="+trade_status);
			if (trade_status.equals("TRADE_FINISHED")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 如果有做过处理，不执行商户的业务程序

				// 注意：
				// 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
			} else if (trade_status.equals("TRADE_SUCCESS")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 如果有做过处理，不执行商户的业务程序
				try{
					flag = serviceTripService.payTripDeposit("", outTradeNo, tradeNo, null, alipay);
				}
				catch(Exception e){
					logger.error(e.getMessage());
				}
				// 注意：
				// 付款完成后，支付宝系统发送该交易状态通知
				// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
			}
			logger.error("paynotify:deposit:alipay:flag="+flag);
			// ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			try {
				if (flag) {
					response.getWriter().write("success");
				} else {
					response.getWriter().write("fail");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} // 请不要修改或删除

			// ////////////////////////////////////////////////////////////////////////////////////////
		} else {// 验证失败
			try {
				logger.error("paynotify:deposit:alipay:verify:fail");
				response.getWriter().write("fail");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value="/tenpay",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
	public void tenpay(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		BufferedReader reader = request.getReader();

		String buffer = null;
		StringBuffer stringBuffer = new StringBuffer();

		while((buffer = reader.readLine()) != null){
			stringBuffer.append(buffer);
		}
		String xmlString  = stringBuffer.toString();
		logger.error("paynotify:deposit:tenpay::xmlString="+xmlString);
		try{
			XStream xstream = XStreamInitializer.getInstance();
			xstream.alias("xml", NotifyMpPayResult.class);
			NotifyMpPayResult notifyMpPayResult = (NotifyMpPayResult) xstream.fromXML(xmlString);
			logger.error("return_code:"+notifyMpPayResult.getReturn_code()+":result_code"+notifyMpPayResult.getResult_code());
			//return_code=SUCCESS and result_code=SUCCESS
			if ("SUCCESS".equalsIgnoreCase(notifyMpPayResult.getReturn_code()) && 
			    "SUCCESS".equalsIgnoreCase(notifyMpPayResult.getResult_code())) {

				WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
				config.setAppId(WxConfig.AppId);
				config.setSecret(WxConfig.AppSecret);
				config.setPartnerId(WxConfig.MchId);
				config.setPartnerKey(WxConfig.SignKey);
				WxMpService wxService = new WxMpServiceImpl();
				wxService.setWxMpConfigStorage(config);		
				
				notifyMpPayResult = wxService.queryOrder(notifyMpPayResult.getOut_trade_no(),"");
				//获取任务订单编号
				String outTradeNo = notifyMpPayResult.getOut_trade_no();
				String transactionId = notifyMpPayResult.getTransaction_id();
				
				Tenpay tenpay = new Tenpay();
				tenpay.setTradeState(notifyMpPayResult.getTrade_state());
				tenpay.setBankType(notifyMpPayResult.getBank_type());
				tenpay.setTransactionId(transactionId);
				tenpay.setDeviceInfo(notifyMpPayResult.getDevice_info());
				tenpay.setIsSubscribe(notifyMpPayResult.getIs_subscribe());
				tenpay.setAttach(notifyMpPayResult.getAttach());
				tenpay.setTimeEnd(notifyMpPayResult.getTime_end());
				tenpay.setFeeType(notifyMpPayResult.getFee_type()+"");
				tenpay.setCashFee(notifyMpPayResult.getCash_fee()+"");
				tenpay.setTradeType(notifyMpPayResult.getTrade_type());
				tenpay.setPayReturnCode(notifyMpPayResult.getReturn_code());
				tenpay.setPayReturnMsg(notifyMpPayResult.getReturn_msg());
				tenpay.setPayResultCode(notifyMpPayResult.getResult_code());
				
				Boolean succeed = false;
				try{
					succeed = serviceTripService.payTripDeposit("", outTradeNo, transactionId, tenpay, null);
					logger.error("paynotify:deposit:tenpay.success="+succeed+",outTradeNo="+outTradeNo);
				}
				catch(Exception e){
					logger.error(e.getMessage());
				}
				if(succeed){
					response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
				}
			}
		}
		catch(Exception e){
			logger.error("paynotify:deposit:tenpay.error"+e.getMessage());
		}
		response.getWriter().write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[修改订单状态失败]]></return_msg></xml>");
		
	}
	
	private String getMapValue(Map<String, String> map, String key){
		if(map == null)
			return "";
		if(map.containsKey(key))
			return map.get(key);
		return "";
	}
	
	@RequestMapping("/alipay/refund")
	public void alipayRefund(@RequestParam(value="tradeNo") String tradeNo){
		String payTradeNo = "";
		Alipay query = new Alipay();
		query.setTradeNo(payTradeNo);
		
		Alipay alipay = alipayService.selectOne("", query);
		if(alipay != null){
			Boolean successed = false;
			try {
				String html = AlipayCore.nopwdRefund(alipay.getOutTradeNo(), alipay.getTradeNo(), alipay.getTotalFee().floatValue(), "用户取消订单退款");
				//successed = AlipayCore.refund(alipay.getOutTradeNo(), alipay.getTradeNo(), alipay.getTotalFee().floatValue(), "用户取消订单退款", "", "", "", "");
				logger.error(html);
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.error("successed="+successed);
		}
	}
	
}
